﻿using ModelHasher;
using ModelHasher.Framework;
using StableDiffusionTools.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using VAELinker.Framework;

namespace VAELinker.Entry
{
    public class EntryModel : EntryBase
    {
        private bool linking = false;

        public EntryVAE LinkedVAE { get; private set; }
        public bool HasSymLinkedVAE { get => LinkedVAE?.IsSymLink ?? false; }
        public bool HasNonSymLinkedVAE { get => !(LinkedVAE?.IsSymLink ?? true); }
        public string LogicalVAEName { get => HasSymLinkedVAE ? LinkedVAE?.VAEName : (LinkedVAE?.FileName ?? ""); }
        public string Hash { get; set; } = null;
        public bool HashHash { get => !string.IsNullOrEmpty(Hash); }

        public EntryModel(string fullName, string root) : base(fullName, root, FileType.Model) { }

        public void Link(EntryVAE vae)
        {
            if (!linking)
            {
                linking = true;
                if (vae == null)
                {
                    LinkedVAE?.Link(null);
                    LinkedVAE = null;
                }
                else
                {
                    LinkedVAE = vae;
                    vae.Link(this);
                }
                linking = false;
            }
        }

        public bool MatchesVAE(EntryVAE entryVAE)
        {
            return $"{entryVAE.PathName}{entryVAE.FileNameNoExtension}".Equals($"{PathName}{FileNameNoExtension}.vae", StringComparison.InvariantCultureIgnoreCase);
        }

        public override void Renamed(string fullName)
        {
            ModelHasherState.State.TryGetModelHashByPathAndName(PathName + FileName, out ModelHash modelHash);

            base.Renamed(fullName);

            if(modelHash != null)
            {
                modelHash.Name = PathName + FileName;
            }

        }

        public bool Rename(string newName)
        {
            try
            {
                string sanitizedName = IOUtil.RemoveIllegalPathCharacters(newName);
                string newPath = Path.Combine(RootDirectory, PathName, newName);
                FileInfo fileInfo = new FileInfo(FullName);
                //fileInfo.MoveTo();
            }
            catch (Exception ex)
            {
                return false;
            }

            return true;
        }
    }
}
